import { createStore } from 'vuex'
import { logApi, loginApi, orderApi } from '@/api'
import { StorageUtil } from '@/utils/storage'
import qs from 'qs'
import { showNotify } from 'vant';
import { moment } from 'moment';

export default createStore({
  state: {
    logs: [],
    logPolling: false,
    logInterval: null,
    autoOpenLogPopup: false,
    active: 0,
    // 是否轮训抢单 
    isAutoGrab: false,
    updateTime: 0, // 十秒
    grabInterval: null,
  },
  mutations: {
    setLogs(state, response) {
      const combinedLogs = [...state.logs, ...response]

      // 按照时间降序排序，确保时间大的日志在数组后面
      combinedLogs.sort((a, b) => {
        const timeA = a.log_time.split(':').map(num => parseInt(num)); // 转为数字数组
        const timeB = b.log_time.split(':').map(num => parseInt(num)); // 转为数字数组
        
        // 比较时、分、秒，降序排序
        for (let i = 0; i < 3; i++) {
          if (timeA[i] !== timeB[i]) {
            return timeB[i] - timeA[i]; // 返回差值（倒序）
          }
        }
        return 0; // 如果时间完全相同
      });
      

      combinedLogs.map(i => {
        // 时间 格式为时分秒不显示年月日
        i.log_time = i.log_time.split(' ').length > 1 ? i.log_time.split(' ')[1] : i.log_time
      })

      state.logs = combinedLogs
    },
    setLogPolling(state, status) {
      state.logPolling = status
    },
    setLogInterval(state, interval) {
      state.logInterval = interval
    },
    setAutoOpenLogPopup(state, status) {
      state.autoOpenLogPopup = status
    },
    setActive(state, index) {
      state.active = index
    },
    setIsAutoGrab(state, index) {
      state.isAutoGrab = index
    },
    setUpdateTime(state, flag) {
      state.isAutoGrab = flag
    },
    setGrabInterval(state, time) {
      state.grabInterval = time
    }
  },
  actions: {
    clearLogs({ state, commit }) {
      state.logs = []
    },
    clearCrabTime({ state, commit, dispatch }) {
      if (state.grabInterval) {
        // 停止之前可能正在播放的音频
        if (window.currentAudio) {
          window.currentAudio.pause();
          window.currentAudio.currentTime = 0;
        }
        clearInterval(state.grabInterval)
        commit('setGrabInterval', null)
        commit('setLogPolling', false)
        commit('setUpdateTime', 0)
      }
    },
    toggleGrab({ state, commit, dispatch }) {
      state.updateTime = 10
      state.grabInterval = setInterval(async () => {
        state.updateTime--

        if (state.updateTime === 0) {
          // 清楚定时器
          clearInterval(state.grabInterval)

          const cardKey = StorageUtil.getCardKey();
          const configForm = await loginApi.login(cardKey)
          const submitData = { ...configForm };

          // 开始抢单
          const res = await orderApi.startGrabOrder(submitData)

          // 开始全局日志轮询
          dispatch('startLogPolling')

          // 弹窗
          showNotify({
            type: 'success',
            message: res,
            duration: 2000
          });
        }
      }, 1000)
    },
    startLogPolling({ state, commit, dispatch }) {
      const cardKey = StorageUtil.getCardKey();
      loginApi.login(cardKey)
        .then(response => {
          commit('setIsAutoGrab', response.always)
        })

      // 仅在未轮询时开始轮询
      if (!state.logPolling) {
        commit('setLogPolling', true)

        const interval = setInterval(() => {
          dispatch('fetchLogs')
        }, 1000)

        commit('setLogInterval', interval)
      } else {
        // 如果已在轮询，立即获取日志
        dispatch('fetchLogs')
      }
    },
    stopLogPolling({ state, commit, dispatch }) {
      if (state.logInterval) {
        commit('setAutoOpenLogPopup', false)
        clearInterval(state.logInterval)
        commit('setLogInterval', null)
        commit('setLogPolling', false)

        if (state.isAutoGrab) {
          showNotify({
            type: 'warning',
            message: '十秒后再次开启抢单！',
            duration: 3000
          });
          dispatch('toggleGrab')
        }
      }
    },
    stopLogPolling2({ state, commit, dispatch }) {
      if (state.logInterval) {
        commit('setAutoOpenLogPopup', false)
        clearInterval(state.logInterval)
        commit('setLogInterval', null)
        commit('setLogPolling', false)
      }
    },
    async fetchLogs({ commit, state, dispatch }) {
      try {
        const cardKey = StorageUtil.getCardKey();

        const param = qs.stringify({
          cardKey: cardKey
        })

        const response = await logApi.getLog(param)

        const newLogs = response.filter(log => log.log_state === 0)
        const errorLogs = response.filter(log => log.log_state === -1)

        // 停止之前可能正在播放的音频
        if (window.currentAudio) {
          window.currentAudio.pause();
          window.currentAudio.currentTime = 0;
        }

        // 错误音乐
        if (errorLogs.length > 0) {
          const audio = new Audio(require('../assets/mp3/qiangdan.mp3'))
          window.currentAudio = audio;
          audio.play().catch(error => {
            console.error('播放错误音频错误:', error)
          })
          dispatch('stopLogPolling')
        }

        // 抢单音乐
        if (newLogs.length > 0) {
          const audio = new Audio(require('../assets/mp3/qiangdan.mp3'))
          window.currentAudio = audio;
          audio.play().catch(error => {
            console.error('播放抢单音频错误:', error)
          })
          dispatch('stopLogPolling')
        }

        commit('setLogs', response)
      } catch (error) {
        console.error('获取日志失败:', error)
        commit('setLogs', [])
      }
    }
  }
})
